import os
import sys
import cv2
import json
import imageio
# import imgaug as ia
# import imgaug.augmenters as iaa
# from imgaug.augmentables.polys import Polygon, PolygonsOnImage

# 使用 via json数据保存标记图像
def via_to_image(data_dir, save_dir):
    with open(data_dir + os.sep + "via_region_data.json","r") as rf:
        data_dict = json.loads(rf.read())
    data_new =  {}

    for filename in data_dict.keys():
        img_name = data_dict[filename]["filename"]
        img_path = data_dir + os.sep + img_name
        image = cv2.imread(img_path)
        for idx,one_label in enumerate(data_dict[filename]["regions"]):
            x = one_label["shape_attributes"]["x"]
            y = one_label["shape_attributes"]["y"]
            width = one_label["shape_attributes"]["width"]
            height = one_label["shape_attributes"]["height"]
            save_path = save_dir + os.sep + ("_"+ str(idx) + ".").join(img_name.split("."))
            cv2.imwrite(save_path, image[y:y+height, x:x+width])
        # data_new[data_dir + os.sep + data_dict[filename]["filename"]] = xys
    #print(len(data_new.keys()))
    # return data_new

if __name__ == "__main__":
    data_dir = "/media/swls/disk1/project/electric_meter_box/20191107"
    save_dir = "/media/swls/disk1/project/electric_meter_box/crop"
    via_to_image(data_dir, save_dir)